package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.lzy.imagepicker.ImagePicker;
import com.mingmen.supplier.R;
import com.mingmen.supplier.adapter.CommodityAllAdapter;
import com.mingmen.supplier.adapter.CommodityRightAdapter;
import com.mingmen.supplier.adapter.NewWeiHuListAdapter;
import com.mingmen.supplier.adapter.NoticeListAdapter;
import com.mingmen.supplier.adapter.WeiHuLeftAllAdapter;
import com.mingmen.supplier.adapter.WeiHuListAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.defineview.WeihuDialog;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.model.CommodityAllModel;
import com.mingmen.supplier.model.CommodityRightModel;
import com.mingmen.supplier.model.WeiHuModel;
import com.mingmen.supplier.popwindow.PopupWindowCompat;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.MyStringUtils;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.mingmen.supplier.util.UtilTool;
import com.mingmen.supplier.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class WeiHuListActivity extends AppCompatActivity implements NewWeiHuListAdapter.OnItemClickListener {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;

    private ImagePicker imagePicker;

    @BindView(R.id.btn_login)
    Button btn_login;

    private int resurtResurant = 100;
    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;

    NewWeiHuListAdapter commodityAdapter;


    LinearLayoutManager linearLayoutManager;


    @BindView(R.id.view_dishline)
    View view_dishline;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    String token;
    String jdataData;
    String date_Send;

    List<WeiHuModel.DataBean.CommoditiesBean> commoditiesBeanList = new ArrayList<>();
    PopupWindowCompat popupWindow;
    @BindView(R.id.text_shucai)
    TextView text_shucai;

    List<WeiHuModel.DataBean> dataBeanList = new ArrayList<>();
    @BindView(R.id.layout_pinlei)
    LinearLayout layout_pinlei;
    @BindView(R.id.commodityName)
    TextView commodityName;
    String categoryId;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    TimePickerView pvTime;
    @BindView(R.id.layout_search)
    LinearLayout layout_search;

    WeihuDialog weihuDialog;
    @BindView(R.id.main_search)
    ClearEditText main_search;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;

    @BindView(R.id.img_jingying)
    ImageView img_jingying;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weihulist);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        linearLayoutManager = new LinearLayoutManager(this);
        token = (String) SharePreferenceUtil.get(this, "token", "");
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        jdataData = getIntent().getStringExtra("jdataData");
        getCaneda();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());

        textview_calendafirst.setText(data);
        date_Send = data;
        mRecyclerView.setLayoutManager(linearLayoutManager);
        commodityAdapter = new NewWeiHuListAdapter(this, commoditiesBeanList);
        mRecyclerView.setAdapter(commodityAdapter);


        commodityAdapter.setDataList(commoditiesBeanList);
        commodityAdapter.setOnItemClickListener(this);

        getData(token, date_Send, "", "0");
        main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                commoditiesBeanList.clear();
                dataBeanList.clear();
                getData(token, date_Send, main_search.getText().toString(), "1");

                return true;
            }
        });
    }


    public void getData(String token, String date_Send, String keyword, String flag) {
        HttpResponse.listCommodityByDate(token, date_Send, keyword, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("WeihuListActivity", s);
                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    WeiHuModel weiHuModel = new WeiHuModel();
                    weiHuModel = GsonUtil.GsonToBean(s, WeiHuModel.class);
//                dataList.addAll(weiHuModel.getData());
                 /*   if (dataBeanList.size() > 0) {
                        commoditiesBeanList.clear();
                        dataBeanList.clear();
                    }*/
                    commoditiesBeanList.clear();
                    dataBeanList.clear();
                    if (weiHuModel.getData().size() > 0) {
                        mRecyclerView.setVisibility(View.VISIBLE);
                        commoditiesBeanList.addAll(weiHuModel.getData().get(0).getCommodities());
                        layout_nodata.setVisibility(View.GONE);
                        text_shucai.setText(weiHuModel.getData().get(0).getCategoryName());
                        commodityName.setText(weiHuModel.getData().get(0).getCommodities().get(0).getCategoryName());
                        categoryId = weiHuModel.getData().get(0).getCategoryId() + "";
                        commodityAdapter.setDataList(commoditiesBeanList);
                        if (flag.equals("0")) {
                            popWindowCreate(weiHuModel.getData());
                        } else {
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(main_search.getWindowToken(), 0);

                        }

                    } else {
                        mRecyclerView.setVisibility(View.GONE);

                        layout_nodata.setVisibility(View.VISIBLE);
                    }
//                    dataBeanList = weiHuModel.getData();

                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(WeiHuListActivity.this, LoginActivity.class));
                } else {
                    Toast.makeText(WeiHuListActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    @OnClick({R.id.text_return, R.id.btn_login, R.id.layout_pinlei, R.id.layout_search, R.id.linear_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_pinlei:
                popupWindow.showAsDropDown(layout_pinlei);
                break;

            case R.id.text_return:
            case R.id.linear_return:
                finish();
                break;
            case R.id.btn_login:

                List<String> jDataList = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                for (int i = 0; i < commoditiesBeanList.size(); i++) {
                    try {
                        jsonObject.put("commodityId", commoditiesBeanList.get(i).getCommodityId());

                        jsonObject.put("price", commoditiesBeanList.get(i).getTodayPrice());
                        jsonObject.put("amount", commoditiesBeanList.get(i).getAddKucun());
                        jsonObject.put("state", commoditiesBeanList.get(i).getState());
                        jDataList.add(jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                HttpResponse.setPrice(token, date_Send, categoryId, jDataList.toString(), new StringCallback(this) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("setPricesetPrice", s);
                        BaseBean baseBean = new BaseBean();
                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                        if (baseBean.getCode() == 0) {
                            finish();
                        } else {

                        }
                        Toast.makeText(WeiHuListActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }
                });

                break;
            case R.id.layout_search:

                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);

                pvTime.show(layout_search);
                break;
        }
    }


    @Override
    public void onItemClickListener(View view, int pos, List<WeiHuModel.DataBean.CommoditiesBean> myLiveList) {
        switch (view.getId()) {
            case R.id.text_price:
                weihuDialog = new WeihuDialog(this);
                weihuDialog.setVerifyClickListener("价格", new WeihuDialog.VerifyClickListener() {
                    @Override
                    public void cancel() {
                    }

                    @Override
                    public void send(String str) {
                        myLiveList.get(pos).setTodayPrice(str);
                        commodityAdapter.notifyDataSetChanged();
                    }
                });
                weihuDialog.show();
                break;
            case R.id.text_kucun:
                weihuDialog = new WeihuDialog(this);
                weihuDialog.setVerifyClickListener("价格", new WeihuDialog.VerifyClickListener() {
                    @Override
                    public void cancel() {
                    }

                    @Override
                    public void send(String str) {
                        myLiveList.get(pos).setAddKucun(str);
                        commodityAdapter.notifyDataSetChanged();
                    }
                });
                weihuDialog.show();
                break;
        }
    }

    public void popWindowCreate(List<WeiHuModel.DataBean> dataBeanList) {
//        CommodityFragment
        popupWindow = new PopupWindowCompat(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_weihu, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(contentView);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        TextView textView = contentView.findViewById(R.id.tv_kdd);
        textView.setText("");
        LinearLayout layout_content = contentView.findViewById(R.id.layout_content);
        layout_content.getBackground().setAlpha(180);
        RecyclerView recyclerView = contentView.findViewById(R.id.recycler_view);
        RecyclerView recycler_right = contentView.findViewById(R.id.recycler_right);

        for (int i = 0; i < dataBeanList.size(); i++) {
            Log.d("dadaaddds", dataBeanList.size() + "");
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(WeiHuListActivity.this, DividerItemDecoration.VERTICAL);
        recycler_right.setLayoutManager(new LinearLayoutManager(this));
        divider.setDrawable(ContextCompat.getDrawable(WeiHuListActivity.this, R.drawable.custom_divider));
//        recyclerView.addItemDecoration(divider);
        WeiHuLeftAllAdapter weiHuLeftAllAdapter = new WeiHuLeftAllAdapter(WeiHuListActivity.this, dataBeanList);

        recyclerView.setAdapter(weiHuLeftAllAdapter);
        weiHuLeftAllAdapter.setOnItemClickListener(new WeiHuLeftAllAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position, List<WeiHuModel.DataBean> mListData) {
                commoditiesBeanList.clear();
                commoditiesBeanList.addAll(mListData.get(position).getCommodities());
                commodityAdapter.setDataList(commoditiesBeanList);
                commodityAdapter.setCheckedPosition(position);
                commodityAdapter.notifyDataSetChanged();
                Log.d("getCommodities", MyStringUtils.beanToString(mListData.get(position).getCommodities()));
//                Toast.makeText(WeiHuListActivity.this, position + "", Toast.LENGTH_SHORT).show();
                text_shucai.setText(mListData.get(position).getCategoryName());
                commodityName.setText(mListData.get(position).getCategoryName());
                categoryId = mListData.get(position).getCategoryId() + "";
                popupWindow.dismiss();

            }


        });


    }

    public void getCaneda() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(2021, 12, 12);
        pvTime = new TimePickerBuilder(WeiHuListActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_search:
                        textview_calendafirst.setText(getTime(date));
                        date_Send = getTime(date);
                        getData(token, date_Send, "", "0");
                        break;

                }

            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);

                                img_jingying.setRotation(180);
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);

                                img_jingying.setRotation(180);
                                pvTime.dismiss();
                            }
                        });

                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))
                .setOutSideCancelable(false)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}




